package net.lbtech.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import net.lbtech.service.GetIaqConfig;
import net.lbtech.service.GetWeather;
import net.lbtech.service.SaveIndoorAir;
import net.lbtech.util.WifiDataFormatUtil;
import net.lbtech.util.exception.GetIaqConfigException;
import net.lbtech.util.exception.SaveIndoorAirException;
import net.lbtech.util.exception.WeatherException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;

public class SimpleChatServerHandler extends SimpleChannelInboundHandler<byte[]> { // (1)

    public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    protected static Logger logger = LoggerFactory.getLogger(SimpleChatServerHandler.class);
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {  // (2)
        Channel incoming = ctx.channel();
        for (Channel channel : channels) {
            channel.writeAndFlush("[SERVER] - " + incoming.remoteAddress() + " 加入\n");
        }
        channels.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {  // (3)
        Channel incoming = ctx.channel();
        for (Channel channel : channels) {
            channel.writeAndFlush("[SERVER] - " + incoming.remoteAddress() + " 离开\n");
        }
        channels.remove(ctx.channel());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception { // (5)
        Channel incoming = ctx.channel();
        System.out.println("SimpleChatClient:"+incoming.remoteAddress()+"在线");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception { // (6)
        Channel incoming = ctx.channel();
        System.out.println("SimpleChatClient:"+incoming.remoteAddress()+"掉线");
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (7)
        Channel incoming = ctx.channel();
        System.out.println("SimpleChatClient:" + incoming.remoteAddress() + "异常");
        // 当出现异常就关闭连接
        cause.printStackTrace();
        ctx.writeAndFlush(WifiDataFormatUtil.errorReturn((byte)0x83));
        ctx.close();
    }



//    @Override
//    protected void messageReceived(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
//        System.out.println("接收到的"+msg.toString());
//        ctx.writeAndFlush("[从服务器返回]" + msg + "\n");
//    }

    @Override
    protected void messageReceived(ChannelHandlerContext ctx, byte[] msg) throws GetIaqConfigException, WeatherException, SaveIndoorAirException, InterruptedException {
        logger.debug("开始接收");
        String outStr = "";
        for (int i = 0; i < msg.length; i++) {
            outStr = outStr+i + ":" + msg[i] + "||";
        }
        //设置空气监控仪
        logger.debug("接收数据："+outStr);
        if (msg[1] == 0x01 && msg[0] == (byte)0xF5) {
            ctx.writeAndFlush(GetIaqConfig.getIaqConfig(msg));
        }
        //获取当地天气情况
        else if (msg[1] == 0x02 && msg[0] == (byte)0xF5) {
            ctx.writeAndFlush(GetWeather.getWeather(msg));
        }
        //保存空气检测仪数据
        else if (msg[1] == 0x03 && msg[0] == (byte)0xF5) {
            ctx.writeAndFlush(SaveIndoorAir.saveIndoorAir(msg));
        }
//        //返回错误
//        else {
//            ctx.writeAndFlush(WifiDataFormatUtil.errorReturn((byte)0x81));
//        }
        logger.debug("接收完成");
    }
}